<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');



class APP_Model extends CI_Model{



	public $validation_errors = array();

	public $isValid = true;

	public $error_message = '';

	protected $binding = '';

	public $id = false;



	public function __construct(){

		parent::__construct();

		$this->load_binding();

		$this->init();

	}

	

	public function init(){

		define('U', $this->config->item('base_url') );

	}

	

	public function validate($data){
		
		$this->validation_errors = array();

		$this->isValid = true;

		

		foreach($this->binding as $n=>$b){

			if( isset( $data[$n] ) && isset($b['validation']) ){

				foreach($b['validation'] as $v){

					$rule = $v['rule'];

					if( array_key_exists('param', $v) ){

						$param = $v['param'];
						if(strpos($param, '$') == 0){
							$param = str_replace('$', '', $param);
							if(isset($data[$param])){
								$param = $data[$param];	
							}else{
								continue;	
							}
						}

					}else{

						$param = null;

					}

					$message = $v['message'];

					if($this->_validate($rule, $data[$n], $param) === false){

						$this->validation_errors[$n] = $message;

						$this->isValid = false;

						break;

					}else{
					}

				}

			}

		}

		return $this->isValid;

	}

	

	private function _validate($rule, $value, $param = null){

		if(method_exists($this, $rule) ){

			return $this->{$rule}($value, $param);

		}else{

			return $this->form_validation->{$rule}($value, $param);

		}

	}	

	

	private function load_binding(){

		if($this->binding == '') return false;

		require BASE_PATH.'application/models/bindings/'.$this->binding.'.php';

		$this->binding = $binding;

		return true;

	}

	

	public function prepare_to_save($data){

		foreach($data as $name=>$value){

			if(!isset($this->binding[$name]) || (isset($this->binding[$name]['save']) && $this->binding[$name]['save'] === false) ){

				unset($data[$name]);

			}

		}

		return $data;

	}

	

	

	

	







}